#!/bin/bash

#echo "General Fixup for: $1"

export DEVPKG_ROOT=/home/andrew/dest-opkg
export NAND_ROOT=/home/andrew/OpenPandora/My_Image

retval=0

# unconfigured ipks still on NAND (shouldn't happen)
if [ ! -e /home/andrew/dest-opkg/usr/lib/opkg/info/$1.list ]
then
	exit 0
fi

while read file
do
	if [ "$file" == "" ]
	then
		continue
	fi
	
	if [ ${file: -3} == .la ]
	then
		#Remove libtool file
		rm -f $file
		continue
	fi
	
	if [ ${file: -3} == .pc ]
	then
		#Modify pkgconfig file
		sed -i -e 's:^includedir=/usr:includedir=${prefix}:' $file
		sed -i -e 's:^libdir=/usr:libdir=${prefix}:' $file
		continue
	fi
	
	# test for symlink
	if [ -h $file ]  
	then
		target=$(file $file | cut -d\` -f2 | cut -d\' -f1)
		
		#relative link
		if [ "${target:0:1}" != "/" ]
		then
			target=${file%/*}"/"$target
			
			#target for symlink is not in DevPKG root
			if [ ! -e $target ]
			then
				target=$(echo $target | sed "s:$DEVPKG_ROOT::")
				
				#target for symlink is not on NAND either
				if [ ! -e $NAND_ROOT$target ]
				then
					echo "ERROR: cannot find target for symlink $file"
					let retval=1
				else
					#Resymlink file to target on NAND root
					ln -sf $NAND_ROOT$target $file
				fi
			fi
		# absolute link
		else
			# avoid error if we're refixing
			if [ -e $target ]
			then
				continue
			fi
			# target is not on NAND root
			if [ ! -e $NAND_ROOT$target ]
			then
				# target is not in DEVPKG_ROOT either
				if [ ! -e $DEVPKG_ROOT$target ]
				then
					echo "ERROR: cannot find target for symlink $file"
					let retval=1
				else
					#Resymlink file to target on DEVPKG root
					ln -sf $DEVPKG_ROOT$target $file
				fi
			fi	
		fi
		
		continue
	fi
	
	#test for library
	if [[ ${file##*/} == lib*so*  ]]
	then
		#New library found.  Add its directory to home/ld.so.cfg.all
		echo "${file%/*}" >> home/ld.so.cfg.all
		
		#After opkg has finished, unique entries in ld.so.cfg.all
		#will be put in /home/ld.co.cfg and ldconfig ran against that.
	fi
done < /home/andrew/dest-opkg/usr/lib/opkg/info/$1.list

#echo "at this point we'd try to download specific fixup for $1"

#echo "and then run it from this script"

if [ -e $DEVPKG_ROOT/home/$1.fixup ]
then
	. $DEVPKG_ROOT/home/$1.fixup
fi

exit $retval

